package com.hb.trade.server.center.au.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hb.core.pojo.center.au.dto.OrgCustomConfigAuditDTO;
import com.hb.core.pojo.center.au.dto.OrgCustomConfigDTO;
import com.hb.core.pojo.center.au.dto.OrgCustomConfigQueryDTO;
import com.hb.core.pojo.center.au.entity.Org;
import com.hb.core.pojo.center.au.entity.OrgCustomConfig;
import com.hb.core.pojo.parent.CopyOperation;
import com.hb.core.pojo.parent.MPBaseController;
import com.hb.core.pojo.parent.MPCommonEntity;
import com.hb.core.pojo.parent.PageResult;
import com.hb.trade.server.center.au.manager.OrgCustomConfigManager;
import com.hb.trade.server.center.au.service.OrgCustomConfigService;
import com.hb.trade.server.center.au.service.OrgService;
import org.fzzn.core.model.enums.AuditStatusEnum;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.Enums;
import org.fzzn.core.util.IdUtil;
import org.fzzn.core.util.MsgUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 企业专属配置信息 前端控制器
 *
 * @author zhaojk
 * @since 2022-04-12
 */
@RefreshScope
@RestController
public class OrgCustomConfigController extends MPBaseController<OrgCustomConfig, OrgCustomConfigService> {

    /**
     * 企业专属定制配置后缀名
     * from: public.yaml
     */
    @Value("${deploy.platformSuffix:赢标电子招采平台}")
    protected String platformSuffix;

    /**
     * 平台部署模式(1: saas部署, 2: 私有化部署)
     * from: public.yaml
     *
     * @see com.hb.core.pojo.center.au.dto.OrgCustomConfigDTO.DeployModeEnum
     */
    @Value("${deploy.mode:1}")
    protected Integer deployMode;

    protected final OrgService orgService;

    public OrgCustomConfigController(OrgCustomConfigService service, OrgService orgService) {
        super(service);
        this.orgService = orgService;
    }

    /**
     * 维护企业专属配置信息
     * 当前部署模式为saas时, 限定logoName2-6个字
     * 当前部署模式为私有化部署时, 限定logoName2-20个字
     *
     * @param configDTO
     * @return
     */
    @PostMapping("/orgCustomConfig/updateConfig")
    public Message<Boolean> updateConfig(@RequestBody OrgCustomConfigDTO configDTO) {
        Long orgId = configDTO.getOrgId();
        if (orgId == null) {
            return MsgUtil.msg(MsgEnum.LOGIN_ERROR);
        }

        OrgCustomConfigManager customConfigManager = configDTO.to(OrgCustomConfigManager.class);
        // 根据部署模式验证 logoName 的长度限制
        String validMsg = customConfigManager.validLogoName(deployMode);
        if (StrUtil.isNotEmpty(validMsg)) {
            return MsgUtil.fail(validMsg);
        }

        // 验证是否有重复域名记录
        String msg = customConfigManager.repeatCount(configDTO.getOrgId());

        // 更新逻辑, 没有id并且没有orgId参数, 执行新增
        if (StrUtil.isEmpty(msg)) {
            // 生成实体类
            OrgCustomConfig customConfig = customConfigManager.to(OrgCustomConfig.class);

            QueryWrapper<OrgCustomConfig> wrapper = OrgCustomConfig.wrapper();
            wrapper.eq("org_id", orgId);
            OrgCustomConfig rawOrgCustomConfig = service.getOne(wrapper);

            if (rawOrgCustomConfig == null) {
                customConfig.setId(IdUtil.getId());
                // 修改审核状态
                customConfig.setAuditStatus(AuditStatusEnum.WAITING.getCode());
                customConfig.setCreateTime(LocalDateTime.now());
                boolean save = service.save(customConfig);
                return MsgUtil.success(save);
            }

            // 修改审核状态
            customConfig.setUpdateTime(LocalDateTime.now());
            customConfig.setAuditStatus(AuditStatusEnum.WAITING.getCode());
            customConfig.to(rawOrgCustomConfig);
            boolean update = service.updateById(rawOrgCustomConfig);

            return MsgUtil.success(update);
        }
        return MsgUtil.fail(msg);
    }

    /**
     * 查询企业专属配置信息
     *
     * @param configDTO
     * @return
     */
    @PostMapping("/orgCustomConfig/settingInfo")
    public Message<OrgCustomConfigDTO> settingInfo(@RequestBody OrgCustomConfigDTO configDTO) {
        // 查询已存在的专属定制信息
        Long orgId = configDTO.getOrgId();
        QueryWrapper<OrgCustomConfig> wrapper = OrgCustomConfig.wrapper();
        wrapper.lambda().eq(OrgCustomConfig::getOrgId, orgId);
        if (null != configDTO.getAuditStatus()) {
            wrapper.lambda().eq(OrgCustomConfig::getAuditStatus, configDTO.getAuditStatus());
        }

        OrgCustomConfig orgCustomConfig = service.getOne(wrapper);

        if (orgCustomConfig == null) {
            orgCustomConfig = new OrgCustomConfig();
        }

        orgCustomConfig.setCompanyLevel(1);
        // 即使是主公司也需要返回前端需要用
        orgCustomConfig.setAuditStatusByMain(orgCustomConfig.getAuditStatus());

        OrgCustomConfigDTO childEntity = ReflectUtil.newInstanceIfPossible(OrgCustomConfigDTO.class);
        BeanUtil.copyProperties(orgCustomConfig, childEntity, CopyOptions.create().ignoreNullValue());

        // 根据不同的部署模式设置不同的后缀
        OrgCustomConfigDTO.DeployModeEnum modeEnum = Enums.of(OrgCustomConfigDTO.DeployModeEnum.class, deployMode);
        switch (modeEnum) {
            case SAAS:
                childEntity.setSuffixName(platformSuffix);
                break;
            case PRIVATIZATION:
                childEntity.setSuffixName(StrUtil.EMPTY);
            default:
                break;
        }

        return MsgUtil.success(childEntity);
    }

    /**
     * 企业专属配置审核列表
     *
     * @param configDTO
     * @return
     */
    @PostMapping("/orgCustomConfig/auditList")
    public Message<PageResult<OrgCustomConfigDTO>> auditList(@RequestBody OrgCustomConfigQueryDTO configDTO) {
        PageResult<OrgCustomConfigDTO> result = service.pageAudit(configDTO);
        return MsgUtil.success(result);
    }

    /**
     * 审核通过/拒绝
     *
     * @param configDTO
     * @return
     */
    @PostMapping("/orgCustomConfig/audit")
    public Message<Boolean> audit(@RequestBody OrgCustomConfigAuditDTO configDTO) {
        Long id = configDTO.getId();
        OrgCustomConfig customConfig = getById(id);
        if (customConfig == null) {
            return MsgUtil.msg(MsgEnum.NULL_RESULT);
        }
        customConfig.setAuditStatus(configDTO.getAuditStatus());
        customConfig.setReason(configDTO.getAuditReason());
        customConfig.setAuditTime(LocalDateTime.now());

        customConfig.buildBaseData(2);
        boolean saveOrUpdate = saveOrUpdate(customConfig);
        return MsgUtil.success(saveOrUpdate);
    }

    /**
     * 查看驳回信息
     *
     * @param configDTO
     * @return
     */
    @PostMapping("/orgCustomConfig/rejectInfo")
    public Message<String> rejectInfo(@RequestBody OrgCustomConfigAuditDTO configDTO) {
        QueryWrapper<OrgCustomConfig> wrapper = OrgCustomConfig.wrapper("reason");
        wrapper.eq("id", configDTO.getId());
        OrgCustomConfig config = service.getOne(wrapper);
        if (config == null) {
            return MsgUtil.msg(MsgEnum.NULL_RESULT);
        }
        return MsgUtil.success(config.getReason());
    }

    /**
     * 根据signKey获取当前企业的自定义信息
     *
     * @param signKey
     * @return
     */
    @GetMapping("/orgCustomConfig/displayConfigInfo")
    public Message<OrgCustomConfigDTO> displayConfigInfo(Integer signKey) {
        if (signKey == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        QueryWrapper<OrgCustomConfig> wrapper = OrgCustomConfig.wrapper();
        wrapper.lambda().select(
                OrgCustomConfig::getOrgId,
                OrgCustomConfig::getLogoName,
                OrgCustomConfig::getLogoUrl1,
                OrgCustomConfig::getLogoUrl2,
                OrgCustomConfig::getLogoUrl3,
                OrgCustomConfig::getOrgPhone,
                OrgCustomConfig::getOrgAddress,
                OrgCustomConfig::getOrgEmail,
                OrgCustomConfig::getDomainNameTrade,
                OrgCustomConfig::getDomainNamePortal,
                OrgCustomConfig::getDomainNameExpert);

        // 查询指定企业的专属定制信息
        wrapper.eq("sign_key", signKey)
                .eq("audit_status", AuditStatusEnum.PASSED.getCode())
                .last("limit 1");
        OrgCustomConfig config = service.getOne(wrapper);

        if (config == null) {
            wrapper.clear();
            wrapper.eq("custom_name", "default");
            config = service.getOne(wrapper);
        }

        OrgCustomConfigDTO configDTO = new OrgCustomConfigDTO();
        BeanUtil.copyProperties(config, configDTO, CopyOptions.create().ignoreNullValue());
        Long orgId = configDTO.getOrgId();
        if (orgId != null) {
            Org org = orgService.getById(orgId);
            configDTO.setOrgName(org.getOrgName());
        }

        // 重新设置平台名称
        String logoName = configDTO.getLogoName();
        OrgCustomConfigDTO.DeployModeEnum modeEnum = Enums.of(OrgCustomConfigDTO.DeployModeEnum.class, deployMode);
        switch (modeEnum) {
            case SAAS:
                configDTO.setLogoName(logoName + platformSuffix);
                break;
            case PRIVATIZATION:
            default:
                break;
        }

        return MsgUtil.success(configDTO);
    }
}
